package cn.getech.data.development.utils.oozie;

import cn.getech.data.development.constant.ScheduleRepeatType;
import cn.getech.data.development.constant.WorkFlowType;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.time.LocalDateTime;


public class CoordinatorUtil {

    public String creatCoordinatorXml( Integer jobId,Integer type){
        try{
            Document document = DocumentHelper.createDocument();
            Element coordinatorApp = document.addElement("coordinator-app");
            coordinatorApp.addAttribute("name",WorkFlowType.ObjOf(type).getEnName() + jobId.toString())
                    .addAttribute("frequency","${frequency}")
                    .addAttribute("start","${startTime}")
                    .addAttribute("end","${endTime}")
                    .addAttribute("timezone", "UTC")
                    .addNamespace("xmlns", "uri:oozie:coordinator:0.2");

            Element action = coordinatorApp.addElement("action");
            Element workflow = action.addElement("workflow");
            Element appPath = workflow.addElement("app-path");
            appPath.setText("${workflowAppUri}");
            Element configuration = workflow.addElement("configuration");
            Element property = configuration.addElement("property");
            property.addElement("name").setText("jobTracker");
            property.addElement("value").setText("${jobTracker}");
            Element property2 = configuration.addElement("property");
            property2.addElement("name").setText("nameNode");
            property2.addElement("value").setText("${nameNode}");
            Element property3 = configuration.addElement("property");
            property3.addElement("name").setText("queueName");
            property3.addElement("value").setText("${queueName}");

            return document.asXML();
        }catch (Exception e){

        }
        return "";
    }

    public String creatCoordinatorXml(String elFunc, Integer jobId,Integer type){
        try{
            Document document = DocumentHelper.createDocument();
            Element coordinatorApp = document.addElement("coordinator-app");
            coordinatorApp.addAttribute("name", WorkFlowType.ObjOf(type).getEnName()+ jobId.toString())
                    .addAttribute("frequency","${"+elFunc+"}")
                    .addAttribute("start","${startTime}")
                    .addAttribute("end","${endTime}")
                    .addAttribute("timezone", "UTC")
                    .addNamespace("xmlns", "uri:oozie:coordinator:0.2");

            Element action = coordinatorApp.addElement("action");
            Element workflow = action.addElement("workflow");
            Element appPath = workflow.addElement("app-path");
            appPath.setText("${workflowAppUri}");
            Element configuration = workflow.addElement("configuration");
            Element property = configuration.addElement("property");
            property.addElement("name").setText("jobTracker");
            property.addElement("value").setText("${jobTracker}");
            Element property2 = configuration.addElement("property");
            property2.addElement("name").setText("nameNode");
            property2.addElement("value").setText("${nameNode}");
            Element property3 = configuration.addElement("property");
            property3.addElement("name").setText("queueName");
            property3.addElement("value").setText("${queueName}");

            return document.asXML();
        }catch (Exception e){

        }
        return "";
    }


    public String time2ELExpresion(String expression,String scheduleOrIntervalCode){
        String frequency = "";
        JSONObject jsonObject = JSONObject.parseObject(expression);

        if (scheduleOrIntervalCode.equals(String.valueOf(ScheduleRepeatType.REPEAT.getCode()))) {
            //循环运行
            if (jsonObject != null) {
                frequency = switchScronType(jsonObject);
            }
        }
        else if (scheduleOrIntervalCode.equals(String.valueOf(ScheduleRepeatType.INTERVAL.getCode())) ){
            //使用其他的方式来进行
            if (jsonObject != null) {
                frequency = switchScronTypeInterval(jsonObject);
            }
        }
        return frequency;
    }


    public static String expressToCron(String expression,String scheduleOrIntervalCode){
        String frequency = "";
        JSONObject jsonObject = JSONObject.parseObject(expression);

        if (scheduleOrIntervalCode.equals(String.valueOf(ScheduleRepeatType.REPEAT.getCode()))) {
            //循环运行
            if (jsonObject != null) {
                frequency = switchScronTypeCron(jsonObject);
            }
        }
        else if (scheduleOrIntervalCode.equals(String.valueOf(ScheduleRepeatType.INTERVAL.getCode())) ){
            //使用其他的方式来进行
            if (jsonObject != null) {
                frequency = switchScronTypeIntervalCron(jsonObject);
            }
        }
        return frequency;
    }

    private static String switchScronTypeInterval(JSONObject jsonObject) {
        String frequency = "";
        if(null != jsonObject){
            switch (jsonObject.getString("type")) {
                case "hour": {
                    frequency = String.format("coord:minutes(%s)", jsonObject.getString("minute"));
//                        frequency = String.format("*/%s * * * *", jsonObject.getString("minute"));
                }
                break;
                case "day": {
                    frequency = String.format("coord:hours(%s)", jsonObject.getString("hour"));
//                        frequency = String.format(LocalDateTime.now().getMinute() + " */%s * * *", jsonObject.getString("hour"));
                }
                break;
                default:
                    break;
            }
        }
        return frequency;
    }

    //间隔的时间用cron表达式无法显示的问题
    private static String switchScronTypeIntervalCron(JSONObject jsonObject) {
        String frequency = "";
        if(null != jsonObject){
            switch (jsonObject.getString("type")) {
                case "hour": {
                        frequency = jsonObject.getString("minute") + "&&minute";
                }
                break;
                case "day": {
                        frequency = jsonObject.getString("hour") + "&&hour";
                }
                break;
                default:
                    break;
            }
        }
        return frequency;
    }

    private static String switchScronType(JSONObject jsonObject) {
        String frequency = "";
        if(null != jsonObject){
            switch (jsonObject.getString("type")) {
                case "hour": {
                    frequency = String.format("%s * * * *", jsonObject.getString("minute"));
                }
                break;
                case "day": {
                    frequency = String.format("%s %s * * *", jsonObject.getString("minute")
                            , jsonObject.getString("hour"));
                }
                break;
                case "week": {
                    frequency = String.format("%s %s * * %s", jsonObject.getString("minute")
                            , jsonObject.getString("hour"), number2Week(jsonObject.getString("week")));
                }
                break;
                case "month": {
                    frequency = String.format("%s %s %s * *", jsonObject.getString("minute")
                            , jsonObject.getString("hour"), jsonObject.getString("day"));
                }
                break;
                default:
                    break;
            }
        }
        return frequency;
    }


    private static String switchScronTypeCron(JSONObject jsonObject) {
        String frequency = "";
        if(null != jsonObject){
            switch (jsonObject.getString("type")) {
                case "hour": {
                    frequency = String.format("0 %s * * * ?", jsonObject.getString("minute"));
                }
                break;
                case "day": {
                    frequency = String.format("0 %s %s * * ?", jsonObject.getString("minute")
                            , jsonObject.getString("hour"));
                }
                break;
                case "week": {
                    frequency = String.format("0 %s %s 0 0 %s", jsonObject.getString("minute")
                            , jsonObject.getString("hour"), number2Week(jsonObject.getString("week")));
                }
                break;
                case "month": {
                    frequency = String.format("0 %s %s %s * ?", jsonObject.getString("minute")
                            , jsonObject.getString("hour"), jsonObject.getString("day"));
                }
                break;
                default:
                    break;
            }
        }
        return frequency;
    }


    public static String number2Week(String num){
        switch (num){
            case "1":
                return "MON";
            case "2":
                return "TUE";
            case "3":
                return "WED";
            case "4":
                return "THU";
            case "5":
                return "FRI";
            case "6":
                return "SAT";
            case "7":
                return "SUN";
        }
        return null;
    }
}
